//
//  ActivityEditViewController.m
//  WindRunner
//
//  Created by leeqb on 9/14/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "ActivityEditViewController.h"
#import "ActivityDetailViewController.h"
#import "AFURLConnectionOperation.h"
#import "AFURLSessionManager.h"
#import "AFHTTPRequestOperationManager.h"

@interface ActivityEditViewController ()
{
    NSInteger _currButtonTag;
    NSData  *_selectedImageData;
    
    NSInteger _dateSelectionType; // 301 开始时间；302 截止时间
    NSDate *_startDate;
    NSDate *_endDate;
    
    UIView *_blackAlphaView;
    
    NSArray *_activityTypes;
    NSArray *_currSelectionItems;
    NSInteger _currPopSelectIndex;
    CGFloat _passwordRowHeight;
}
@end

@implementation ActivityEditViewController

+ (NSArray *)getActivityTypes
{
    NSArray *activityTypes = @[LocalStringSetting(@"UE_ACTIVITY_TYPE1"), LocalStringSetting(@"UE_ACTIVITY_TYPE2"), LocalStringSetting(@"UE_ACTIVITY_TYPE3"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE4"), LocalStringSetting(@"UE_ACTIVITY_TYPE5"), LocalStringSetting(@"UE_ACTIVITY_TYPE6"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE7"), LocalStringSetting(@"UE_ACTIVITY_TYPE8"), LocalStringSetting(@"UE_ACTIVITY_TYPE9"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE10"), LocalStringSetting(@"UE_ACTIVITY_TYPE11"), LocalStringSetting(@"UE_ACTIVITY_TYPE12"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE13"), LocalStringSetting(@"UE_ACTIVITY_TYPE14"), LocalStringSetting(@"UE_ACTIVITY_TYPE15"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE16"), LocalStringSetting(@"UE_ACTIVITY_TYPE17"), LocalStringSetting(@"UE_ACTIVITY_TYPE18"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE19"), LocalStringSetting(@"UE_ACTIVITY_TYPE20"), LocalStringSetting(@"UE_ACTIVITY_TYPE21"),
       LocalStringSetting(@"UE_ACTIVITY_TYPE22"), LocalStringSetting(@"UE_ACTIVITY_TYPE23"), LocalStringSetting(@"UE_ACTIVITY_TYPE24")];
    return activityTypes;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        _passwordRowHeight = 38;
        _activityTypes = [ActivityEditViewController getActivityTypes];
        
        _blackAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _blackAlphaView.backgroundColor = [UIColor blackColor];
        _blackAlphaView.alpha = 0.5f;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = LocalStringEvent(@"NAV_TITLE_CREATE_ACTIVITY");
    _activityTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    _secretSwitcher.delegate = self;
    
    if(self.data) {
        _nameInput.text = [NSString formatString:self.data[@"title"]];
        _locationInput.text = [NSString formatString:self.data[@"location"]];
        _limitInput.text = [NSString formatString:self.data[@"personcount"]];
        _requireInput.text = [NSString formatString:self.data[@"slogan"]];
        
        _passField.text = [NSString formatString:self.data[@"password"]];
        _secretSwitcher.on = [self.data[@"secret"] boolValue];
        _secretSwitcher.userInteractionEnabled = NO;
        _passwordRowHeight = 0;
        _passLabel.hidden = YES;
        _passField.hidden = YES;
        /*if(![self.data[@"secret"] boolValue]) {
            _passwordRowHeight = 0;
        }*/
    }
    [_activityTable reloadData];
    
    NSString *typeString = [NSString formatString:self.data[@"type"]];
    if([typeString isEqualToString:@""]) {
        typeString = @"0";
    }
    _currPopSelectIndex = [typeString integerValue];
    _typeInput.text = _activityTypes[_currPopSelectIndex];
    
    CGRect rect;
    NSString *startTimeString = [NSString formatString:self.data[@"starttime"]];
    NSString *endTimeString = [NSString formatString:self.data[@"endtime"]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"MM-dd HH:mm";
    if(![startTimeString isEqualToString:@""]) {
        _startDate = [NSDate dateWithTimeIntervalSince1970:[startTimeString doubleValue]/1000];
        _timeInput.text = [dateFormatter stringFromDate:_startDate];
        
        rect = _timeInput.frame;
        rect.size.width = _endTimeInput.frame.size.width;
        _timeInput.frame = rect;
        _startTimeButton.frame = rect;
        
        rect = _horLineTime.frame;
        rect.origin.x = _timeInput.frame.origin.x + _timeInput.frame.size.width + 5;
        _horLineTime.frame = rect;
        
        rect = _endTimeInput.frame;
        rect.origin.x = _horLineTime.frame.origin.x + _horLineTime.frame.size.width + 6;
        _endTimeInput.frame = rect;
        _endTimeButton.frame = rect;
    }
    
    if(![endTimeString isEqualToString:@""]) {
        _endDate = [NSDate dateWithTimeIntervalSince1970:[startTimeString doubleValue]/1000];
        _endTimeInput.text = [dateFormatter stringFromDate:_endDate];
    }
    
    NSString *imageUrl = [NSString formatString:self.data[@"imgurl"]];
    if(![imageUrl isEqual:@""]) {
        imageUrl = [NSString stringWithFormat:@"%@%@", IMAGE_URL_PREFIX, imageUrl];
        FMDownloadImage *downloader = [[FMDownloadImage alloc] initWithTarget:_activityImageView];
        [downloader downLoadImageWithURL:imageUrl imagetype:@"ActivityEditImages"];
    }
}

// 如果是私密活动就显示密码输入框，否则不显示
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 1) {
        return _passwordRowHeight;
    }
    
    return 38;
}

- (void)hideKeyboard
{
    [_nameInput resignFirstResponder];
    [_timeInput resignFirstResponder];
    [_endTimeInput resignFirstResponder];
    [_locationInput resignFirstResponder];
    [_requireInput resignFirstResponder];
}

- (void)selectAddress:(UIButton *)button
{
    
}

// 点击回车隐藏键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)saveActivity:(UIButton *)sender {
    NSString *activityType = [NSString formatString:_typeInput.text];
    NSString *activityName = [NSString formatString:_nameInput.text];
    NSString *activityAddr = [NSString formatString:_locationInput.text];
    NSString *activityLimits = [NSString formatString:_limitInput.text];
    NSString *activityRemind = [NSString formatString:_remindInput.text];
    NSString *activityRequire = [NSString formatString:_requireInput.text];
    NSString *password = [NSString formatString:_passField.text];
    BOOL allowSignUp = _applySwitcher.on;
    
    NSString *imgurl = [NSString formatString:self.data[@"imgurl"]];
    if(!_selectedImageData && [imgurl isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_PIC")];
        return;
    }
    
    if([activityType isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_TYPE")];
        return;
    }
    
    if([activityName isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_NAME")];
        return;
    }
    
    if(!_startDate || !_endDate) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_TIME")];
        return;
    }
    
    if([activityAddr isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_ADDR")];
        return;
    }
    
    if([activityRequire isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_REQUIRE")];
        return;
    }
    
    if(_secretSwitcher.on && [password isEqualToString:@""]) {
        [FMToast showMessage:LocalStringEvent(@"ACT_EDIT_TIP_PASSWORD")];
        return;
    }
    
    [_nameInput resignFirstResponder];
    [_locationInput resignFirstResponder];
    [_requireInput resignFirstResponder];
    [_passField resignFirstResponder];
    
    NSTimeInterval startInterval = [_startDate timeIntervalSince1970] * 1000;
    NSTimeInterval endInterval = [_endDate timeIntervalSince1970] * 1000;
    
    NSDictionary *requestData = nil;;
    NSString *urlString = @"";
    if(self.data) { // 修改
        urlString = [NSString stringWithFormat:@"%@activeedit", BASE_API_URL_WINDRUNNER];
        requestData = @{@"id":self.data[@"id"],
                        @"title":activityName,
                        @"type":[NSString stringWithFormat:@"%@", @(_currPopSelectIndex)],
                        @"starttime":[NSString stringWithFormat:@"%lld", (long long)startInterval],
                        @"endtime":[NSString stringWithFormat:@"%lld", (long long)endInterval],
                        @"location":activityAddr,
                        @"locationX":CURR_COORDINATE_X_STR,
                        @"locationY":CURR_COORDINATE_Y_STR,
                        @"personcount":activityLimits,
                        @"warntime":activityRemind,
                        @"slogan":activityRequire,
                        @"allowsign":[NSString stringWithFormat:@"%d", allowSignUp]};
    } else { // 新建
        urlString = [NSString stringWithFormat:@"%@activecreate", BASE_API_URL_WINDRUNNER];
        requestData = @{@"creater":[AuthHelper getCurrentUser][@"id"],
                        @"title":activityName,
                        @"type":[NSString stringWithFormat:@"%@", @(_currPopSelectIndex)],
                        @"starttime":[NSString stringWithFormat:@"%lld", (long long)startInterval],
                        @"endtime":[NSString stringWithFormat:@"%lld", (long long)endInterval],
                        @"location":activityAddr,
                        @"locationX":CURR_COORDINATE_X_STR,
                        @"locationY":CURR_COORDINATE_Y_STR,
                        @"personcount":activityLimits,
                        @"warntime":activityRemind,
                        @"slogan":activityRequire,
                        @"allowsign":[NSString stringWithFormat:@"%d", allowSignUp],
                        @"secret":[NSNumber numberWithBool:_secretSwitcher.on],
                        @"password":_passField.text};
    }
    
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];;
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:requestData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(_selectedImageData) {
            [formData appendPartWithFileData:_selectedImageData name:@"imgurl" fileName:@"ActivityImage.png" mimeType:@"image/png"];
        }
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSProgress *progress = nil;
    
    [FMToast showLoading:LocalStringCommon(@"OPER_DOING")];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if(!error) {
            [FMToast showMessage:LocalStringCommon(@"OPER_SUCC")];
            
            // 将json字符串转换成NSDictionary对象
            NSError *err;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&err];
            
            if(self.data) {
                NSArray *vcs = self.navigationController.viewControllers;
                ActivityDetailViewController *detailController = (ActivityDetailViewController *)vcs[vcs.count-2];
                detailController.data = result[@"record"];
            }
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [FMToast showMessage:LocalStringCommon(@"OPER_FAIL")];
        }
    }];
    
    [uploadTask resume];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _currSelectionItems.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return _currSelectionItems[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _currPopSelectIndex = row;
}

// 弹出活动类型选择框
- (IBAction)showTypeSelectView:(id)sender {
    [self hideKeyboard];
    _currSelectionItems = _activityTypes;
    
    CGRect rect = _popSelectView.frame;
    rect.origin.x = (SCREEN_WIDTH - rect.size.width) / 2;
    rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2;
    _popSelectView.frame = rect;
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:_blackAlphaView];
    [keyWindow addSubview:_popSelectView];
}

// 活动类型选择框点击确定按钮
- (IBAction)typeSelected:(id)sender {
    _typeInput.text = _activityTypes[_currPopSelectIndex];
    
    [_popSelectView removeFromSuperview];
    [_blackAlphaView removeFromSuperview];
}

- (IBAction)selectActivityImage:(id)sender {
    PickImageView *pickView = [[PickImageView alloc] init];
    pickView.delegate = self;
    [pickView show];
}

- (IBAction)selectTime:(UIButton *)sender {
    [self hideKeyboard];
    _dateSelectionType = sender.tag;
    CGRect rect = _popDateSelectView.frame;
    rect.origin.x = (SCREEN_WIDTH - rect.size.width) / 2;
    rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2;
    _popDateSelectView.frame = rect;
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:_blackAlphaView];
    [keyWindow addSubview:_popDateSelectView];
}

// 时间选择后，点击确定按钮
- (IBAction)dateSelected:(id)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"MM-dd HH:mm";
    if(_dateSelectionType == 301) {
        // 开始时间选择后，重新调整坐标
        CGRect rect = _timeInput.frame;
        rect.size.width = _endTimeInput.frame.size.width;
        _timeInput.frame = rect;
        _startTimeButton.frame = rect;
        
        rect = _horLineTime.frame;
        rect.origin.x = _timeInput.frame.origin.x + _timeInput.frame.size.width + 5;
        _horLineTime.frame = rect;
        
        rect = _endTimeInput.frame;
        rect.origin.x = _horLineTime.frame.origin.x + _horLineTime.frame.size.width + 6;
        _endTimeInput.frame = rect;
        _endTimeButton.frame = rect;
        
        _startDate = _datePicker.date;
        _timeInput.text = [dateFormatter stringFromDate:_datePicker.date];
    } else if(_dateSelectionType == 302) {
        _endDate = _datePicker.date;
        _endTimeInput.text = [dateFormatter stringFromDate:_datePicker.date];
    }
    
    [_popDateSelectView removeFromSuperview];
    [_blackAlphaView removeFromSuperview];
}

- (void)imageTypeSelected:(UIImagePickerController *)vc
{
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
    }];
}
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    _selectedImageData = UIImagePNGRepresentation(editedImage);
    editedImage = [UIImage imageWithData:_selectedImageData];
    _activityImageView.image = editedImage;
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark LESwitcherDelegate
- (void)onSwitch:(BOOL)on
{
    if(on) {
        _passwordRowHeight = 38;
        _passLabel.hidden = NO;
        _passField.hidden = NO;
    } else {
        _passwordRowHeight = 0;
        _passLabel.hidden = YES;
        _passField.hidden = YES;
    }
    
    [_activityTable reloadData];
}

@end
